<template>
    <div class="script-manage-dialog-modal-wrapper">
        <el-dialog
            :model-value="props.value"
            :title="dialog.title"
            :width="dialog.width"
            destroy-on-close
            :close-on-click-modal="props.readonly"
        >
            <el-form ref="ruleFormRef" :model="formData" :rules="ruleForm" label-width="120px">
                <div class="form-item-box-one">
                    <div>
                        <el-form-item label="脚本名称" prop="scriptName">
                            <el-input
                                v-model="formData.scriptName"
                                @input="value => (formData.scriptName = value.trim())"
                                placeholder="请输入脚本名称"
                                :disabled="props.readonly"
                                maxlength="50"
                            />
                        </el-form-item>
                        <el-form-item label="脚本类型" prop="scriptType">
                            <el-select v-model="formData.scriptType" :disabled="props.readonly">
                                <el-option
                                    v-for="(value, key) in ScriptType"
                                    :label="value"
                                    :key="key"
                                    :value="key"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </div>
                    <div>
                        <el-form-item label="标识符" prop="scriptNo">
                            <el-input
                                v-model="formData.scriptNo"
                                @input="value => (formData.scriptNo = value.trim())"
                                placeholder="系统自动生成"
                                disabled
                            />
                        </el-form-item>
                    </div>
                </div>
                <el-form-item label="描述" prop="scriptDescription">
                    <el-input
                        v-model="formData.scriptDescription"
                        maxlength="200"
                        show-word-limit
                        type="textarea"
                        placeholder="请输入描述"
                        :disabled="props.readonly"
                    />
                </el-form-item>
                <el-form-item label="脚本内容" prop="scriptContent">
                    <CodeEditor
                        ref="editorRef"
                        theme="vs"
                        :style="{ minHeight: '200px', width: '100%' }"
                        v-model="formData.scriptContent"
                        language="text"
                        lineNumbers="on"
                        @code-error="(err: any) => (error = !!err)"
                        :readOnly="props.readonly"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="props.close">取消</el-button>
                    <el-button type="primary" @click="submitForm" :loading="loading">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus';
import type { ScriptVO } from '@great/services';
import { runScriptService } from '@great/services';
import { CodeEditor } from '@great/components';
import { reactive, ref } from 'vue';
import type { PopupBoxProps } from '@great/utils';
import { useRequest } from 'vue-request';
import { ScriptType } from '@/utils/constant';

const editorRef = ref<any>();

interface IProps extends PopupBoxProps {
    row?: ScriptVO;
    getList?: () => Promise<void>;
    readonly?: boolean;
}
const props = defineProps<IProps>();

interface Dialog {
    title: string;
    width: number | string;
    detail?: ScriptVO;
}
const dialog = reactive<Dialog>({
    title: '新建脚本',
    width: '80%',
    detail: undefined
});

const formData = reactive<ScriptVO>({
    scriptName: '', // 脚本名称
    scriptNo: '', // 标识符
    scriptType: '', // 脚本类型
    scriptContent: '', // 脚本内容
    scriptDescription: '' // 脚本描述
});

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<FormRules>({
    scriptName: [{ required: true, message: '请输入脚本名称', trigger: ['blur', 'change'] }],
    scriptType: [{ required: true, message: '请选择脚本类型', trigger: ['blur', 'change'] }],
    scriptContent: [{ required: true, message: '请输入脚本内容', trigger: ['blur', 'change'] }]
});

// 是否为编辑
const isEdit = (par?: boolean): boolean => {
    if (par === undefined) {
        return dialog.title.includes('修改');
    } else {
        return dialog.title.includes('修改') && par;
    }
};

// 提交接口请求
const { run, loading } = useRequest(
    () => {
        return runScriptService[isEdit() ? 'updateScript' : 'addScript'](formData);
    },
    {
        manual: true,
        onSuccess(res) {
            ElNotification({
                title: isEdit() ? '修改成功！' : '创建成功！',
                type: 'success'
            });
            closeDialog();
        }
    }
);
// 表单提交
const submitForm = () => {
    console.log(formData.scriptContent);
    if (props.readonly) {
        closeDialog();
        return;
    }
    ruleFormRef.value?.validate(valid => {
        valid && run();
    });
};

//关闭弹框
const closeDialog = () => {
    props.close();
    if (props.getList) props.getList();
};

// 打开弹框
const openDialog = () => {
    if (props.row) {
        if (props.readonly) {
            dialog.title = '查看脚本';
        } else {
            dialog.title = '修改脚本';
        }
        dialog.detail = JSON.parse(JSON.stringify(props.row));
        formData.id = props.row.id;
        Object.keys(formData).forEach(key => {
            formData[key] = (props.row as ScriptVO)[key];
        });
    }
};

const init = () => {
    openDialog();
};
init();
</script>
<style scoped lang="scss">
.script-manage-dialog-modal-wrapper {
    .el-form {
        .form-item-box-one {
            display: flex;
            justify-content: space-between;
            > div {
                width: calc((100% - 10px) / 2);
            }
        }
    }
}
</style>
